<template>
	<div class="ue-element-data-source">
    <eSelect v-model="type" transfer @on-change="selectType">
      <eOption v-for="item in types" :key="item" :value="item" :label="item"></eOption>
    </eSelect>
    <CodeEditor v-show="type === 'static'" v-model="code" language="json"></CodeEditor>
    <div v-show="type === 'fetch'">
      <eInput v-model="url" placeholder="请输入接口地址" clearable></eInput>
      <CodeEditor label="返回数据处理函数" v-model="resultFn"></CodeEditor>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'

interface IProps {
	modelValue: Record<string, any> | null | undefined
}

const props = defineProps<IProps>()

const emit = defineEmits<{
  (e: 'update:modelValue', data: Record<string, any>): void
}>()

const fnStr = `function fn(page, data) {
}`

const type = ref<string>('')
const code = ref<string>('')
const url = ref<string>('')
const resultFn = ref<string>(fnStr)
const types = computed(() => ['static', 'fetch'])

function emitValue() {
  emit('update:modelValue', {
    type: type.value,
    value: code.value,
    resultFn: resultFn.value,
    url: url.value
  })
}

watch(
	() => props.modelValue,
	(newVal) => {
		if (newVal) {
      type.value = newVal.type
      code.value = typeof newVal.value === 'object' ? JSON.stringify(newVal.value, null, 2) : newVal.value
      url.value = newVal.url
      resultFn.value = newVal.resultFn || fnStr
    }
	},
	{ immediate: true }
)

function selectType() {
  url.value = ''
  resultFn.value = fnStr
}

watch(
  [code, resultFn],
  emitValue
)
</script>

<style lang="less" scoped>
  .ue-element-data-source {
    width: 100%;
  }
</style>
